package cn.tedu.qxhouserent.house.service.impl;

import cn.tedu.qxhouserent.commons.ex.ServiceException;
import cn.tedu.qxhouserent.commons.web.ServiceCode;
import cn.tedu.qxhouserent.house.mapper.NewsContentMapper;
import cn.tedu.qxhouserent.house.mapper.NewsDetailMapper;
import cn.tedu.qxhouserent.house.pojo.entity.NewsContent;
import cn.tedu.qxhouserent.house.pojo.entity.NewsDetail;
import cn.tedu.qxhouserent.house.pojo.param.NewsDetailAddNewParam;
import cn.tedu.qxhouserent.house.pojo.param.NewsDetailUpdateInfoParam;
import cn.tedu.qxhouserent.house.pojo.vo.NewsDetailListItemVO;
import cn.tedu.qxhouserent.house.pojo.vo.NewsDetailStandardVO;
import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.house.service.NewsDetailService;
import cn.tedu.qxhouserent.commons.util.PageInfoToPageDataConverter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@Transactional
public class NewsDetailServiceImpl implements NewsDetailService {

    @Autowired
    private NewsDetailMapper newsDetailMapper;

    @Autowired
    private NewsContentMapper newsContentMapper;

    @Override
    public void addNew(NewsDetailAddNewParam newsDetailAddNewParam) {
        log.debug("开始处理【添加新闻详情】业务：{}", newsDetailAddNewParam);

        //查看新闻详情中有无相同题目的数据
        log.debug("查看新闻详情中有无相同题目的数据：");
        QueryWrapper<NewsDetail> newsDetailQueryWrapper = new QueryWrapper<>();
        newsDetailQueryWrapper.eq("title", newsDetailAddNewParam.getTitle());
        Integer num = newsDetailMapper.selectCount(newsDetailQueryWrapper);
        log.debug("查询结果：{}", num);

        if (num > 0) {
            String message = "新闻详情中有相同题目的数据，添加失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //开始向news_detail中添加数据
        log.debug("检查通过！开始添加数据：{}", newsDetailAddNewParam);
        NewsDetail newsDetail = new NewsDetail();
        BeanUtils.copyProperties(newsDetailAddNewParam, newsDetail);
        newsDetail.setPublishTime(LocalDateTime.now());
        newsDetail.setGmtModified(LocalDateTime.now());
        log.debug("插入数据为：{}", newsDetail);

        int insert = newsDetailMapper.insert(newsDetail);
        if (insert != 1) {
            String message = "添加资讯详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("插入后的数据为：{}", newsDetail);
        log.debug("添加成功！");

        //开始向news_content中添加数据
        NewsContent newsContent = new NewsContent();
        newsContent.setContent(newsDetailAddNewParam.getContent())
                .setNewsDetailId(newsDetail.getId())
                .setGmtModified(LocalDateTime.now());
        log.debug("开始向news_content中添加数据：{}", newsContent);
        int insert1 = newsContentMapper.insert(newsContent);
        if (insert1 != 1) {
            String message = "添加资讯正文失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("添加成功！newsContent:{}", newsContent);
    }

    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【通过id删除咨询详情】的业务，参数：{}" ,id);

        // 检查新闻详情是否存在，如果不存在，则抛出异常
        QueryWrapper<NewsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById = newsDetailMapper.selectCount(queryWrapper);
        log.debug("根据咨询详情id统计匹配的咨询数量，结果：{}" , countById);
        if (countById==0){
            String message = "删除咨询失败，咨询详情数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int i = newsDetailMapper.deleteById(id);
        if (i != 1) {
            String message = "删除资讯详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("通过id删除咨询详情数据，完成！");

        int i1 = newsContentMapper.deleteByDetailId(id);
        if (i1 != 1) {
            String message = "删除资讯正文失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("通过id删除咨询正文数据，完成！");
    }

    public void updateById(Long id, NewsDetailUpdateInfoParam newsDetailUpdateInfoParam){
        log.debug("开始处理【修改新闻详情】业务：{}", newsDetailUpdateInfoParam);

        // 检查新闻详情是否存在，如果不存在，则抛出异常
        QueryWrapper<NewsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        int countById = newsDetailMapper.selectCount(queryWrapper);
        log.debug("根据新闻详情ID统计匹配的新闻数量，结果：{}", countById);
        if (countById==0){
            String message = "修改新闻详情失败，新闻详情数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //查看新闻详情中有无相同题目的数据
        log.debug("查看新闻详情中有无相同题目的数据：");
        QueryWrapper<NewsDetail> newsDetailQueryWrapper = new QueryWrapper<>();
        newsDetailQueryWrapper.eq("title", newsDetailUpdateInfoParam.getTitle())
                .ne("id", id);
        Integer num = newsDetailMapper.selectCount(newsDetailQueryWrapper);
        log.debug("查询结果：{}", num);

        if (num > 0) {
            String message = "新闻详情中有相同题目的数据，修改失败！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行咨询详情表修改
        NewsDetail newsDetail = new NewsDetail();

        BeanUtils.copyProperties(newsDetailUpdateInfoParam,newsDetail);

        newsDetail.setGmtModified(LocalDateTime.now());
        newsDetail.setId(id);
        log.debug("输出咨询详情表：{}",newsDetail);
        int i = newsDetailMapper.updateById(newsDetail);
        if (i != 1) {
            String message = "更新资讯详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

        //执行咨询正文修改
        NewsContent newsContent = new NewsContent();
        newsContent.setNewsDetailId(id);
        newsContent.setContent(newsDetailUpdateInfoParam.getContent());
        log.debug("输出咨询正文：{}",newsContent);
        int i1 = newsContentMapper.updateByDetailId(newsContent);
        if (i1 != 1) {
            String message = "更新资讯正文失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的新闻数据更新入到数据库，完成！");

    }

    //资讯详情列表
    @Override
    public PageData<NewsDetailListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<NewsDetailListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询咨询详情列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<NewsDetailListItemVO> list = newsDetailMapper.list();
        PageInfo<NewsDetailListItemVO> pageInfo = new PageInfo<>(list);
        PageData<NewsDetailListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    //根据ID查询咨询详情
    @Override
    public NewsDetailStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询咨询详情】的业务，参数：{}", id);
        NewsDetailStandardVO queryResult = newsDetailMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询咨询详情详情失败，数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }



}
